package com.zyx.xunyilu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyx.xunyilu.entity.User;
import com.zyx.xunyilu.enums.RegisterStatus;
import com.zyx.xunyilu.mapper.UserMapper;
import com.zyx.xunyilu.service.UserService;
import com.zyx.xunyilu.utils.CacheUtils;
import com.zyx.xunyilu.utils.CodeDesUtils;
import com.zyx.xunyilu.utils.EmailUtils;
import com.zyx.xunyilu.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName: EmailController
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/11/12 23:14
 */
@CrossOrigin
@Slf4j
@Controller
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private CacheUtils cacheUtils;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/auth")
    public String authView() {
        return "auth";
    }

    /**
     * 邮箱验证API
     * @param nameCode  用户名
     * @param emailCode 用户邮箱
     * @param code      随机值
     * @return  返回是否更新成功
     * @throws Exception    解码异常
     */
    @ResponseBody
    @PostMapping("/check")
    public RestResponse auth(@RequestParam("s") String nameCode,
                             @RequestParam("t") String emailCode,
                             @RequestParam("code") String code) throws Exception {
        try {
            String codeCache = (String) cacheUtils.get("code");
            if (StringUtils.isEmpty(codeCache)) {
                return RestResponse.fail("抱歉！验证码失效！请重试！");
            }
            if (!codeCache.equals(code)) {
                return RestResponse.fail("验证链接失效！请重试！");
            }

            String name = CodeDesUtils.decryption(nameCode);
            String email = CodeDesUtils.decryption(emailCode);

            User user = userMapper.selectOne(new QueryWrapper<User>().eq("name", name).eq("email", email));
            user.setRegister(RegisterStatus.IS_REGISTER);
            if (userMapper.updateById(user) > 0) {
                return RestResponse.ok(user);
            }
            return RestResponse.fail("失败");
        } catch (Exception e) {
            log.error("{} -名称解码失败", nameCode);
            throw e;
        }
    }

}

